package com.jinyuanchun.learnjava.service.impl;

import com.jinyuanchun.learnjava.service.LdapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.support.LdapUtils;
import org.springframework.stereotype.Service;

import javax.naming.directory.DirContext;

@Service
public class LdapServiceImpl implements LdapService {
    @Autowired
    private LdapTemplate ldapTemplate;

    @Override
    public boolean authenticate(String usr, String credentials) {
        String userDn = usr+"@genomics.cn";
        DirContext ctx = null;
        try {
            ctx = ldapTemplate.getContextSource().getContext(userDn, credentials);
            return true;
        } catch (Exception e) {
            // Context creation failed - authentication did not succeed
            return false;
        } finally {
            // It is imperative that the created DirContext instance is always closed
            LdapUtils.closeContext(ctx);
        }
    }
}
